import axios from 'axios'
import { ISignin } from '../interface/screeps.interface'
import ProcessEnv from '../config/config.default'
// import playerService from '../db/service/player.service'

axios.defaults.baseURL = 'https://screeps.com/api'
axios.defaults.timeout = 3000

let token = ''

const getToken = () => {
    return axios.post<ISignin>('/auth/signin', {
        email: ProcessEnv.STEAM_EMAIL,
        password: ProcessEnv.STEAM_PWD,
    })
}

const init = async () => {
    const res = await getToken()
    if (res.data.ok) {
        token = res.data.token
    }
}
init()

/**
 * 请求拦截器：添加token
 */
axios.interceptors.request.use(async (config) => {
    if (config.headers) config.headers['X-Token'] = token
    return config
})

/**
 * token失效拦截
 * token失效则重新发起获取token
 */
axios.interceptors.response.use(
    async (response) => {
        if (response.data.error && response.data.error === 'unauthorized') {
            const res = await getToken()
            if (res.data.ok) {
                // 把获取到的token写入数据库
                // await playerService.setToken(ProcessEnv.SCREEPSNAME, res.data.token)
                token = res.data.token
            }
        } else {
            if (response.headers['x-token']) token = response.headers['x-token'] as string
        }
        return response
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error)
    },
)

export default axios
